package sc.tool.sqlgen.branchinfo;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.helpers.XMLUtils;
import org.springframework.util.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import sc.prototype.common.ConsoleUtil;

/**
 *
 * <p>工行文件解析器</p>
 * @author Zhang Yun
 * @version $Id: ICBCParser.java, v 0.1 2012-11-3 下午11:34:44 User Exp $
 */
public class ICBCParser implements Parser, ConsoleUtil {

    static final List<String> ignoreIbpsCodes = Arrays.asList("000");

    @Override
    public ParseResult parse(File sourceDataFile) {
        ParseResult parseResult = new ParseResult();

        try {
            Document doc = XMLUtils.parse(sourceDataFile);
            XPathFactory factoryXpah = XPathFactory.newInstance();
            XPath xpath = factoryXpah.newXPath();
            XPathExpression expr;

            //
            expr = xpath.compile("//ibps");
            NodeList ibpsList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < ibpsList.getLength(); i++) {
                Node ibps = ibpsList.item(i);
                String ibpsCode = ibps.getAttributes().getNamedItem("code").getTextContent();
                if (ignoreIbpsCodes.contains(ibpsCode)) {
                    Console.info("ignore ibps[{}]", ibpsCode);
                    continue;
                }

                NodeList ibpsNameList = ibps.getChildNodes();
                if (ibpsNameList == null) {
                    continue;
                }
                //

                //            expr = xpath.compile("//ibpsName");

                //            Object result = expr.evaluate(doc, XPathConstants.NODESET);
                //            NodeList nodes = (NodeList) result;

                for (int j = 0; j < ibpsNameList.getLength(); j++) {
                    Node node = ibpsNameList.item(j);
                    if (node.getAttributes() == null) {
                        continue;
                    }
                    String branchId = null;
                    try {
                        //TODO:检验信息
                        BranchInfo bi = new BranchInfo();
                        branchId = node.getAttributes().getNamedItem("paySysBankCode").getTextContent();
                        bi.setBranchId(branchId);
                        bi.setUnifiedBankId(DataService.getUnifiedBankId(branchId));
                        bi.setBranchName(node.getAttributes().getNamedItem("name").getTextContent());

                        Area area = DataService.getAreaByBranchId(bi.getBranchId());
                        Assert.notNull(area, "找不到地区[" + DataService.getAreaCode(branchId) + "]");

                        Bank bank = DataService.getBankByBranchId(branchId);
                        Assert.notNull(bank, "找不到银行[" + DataService.getUnifiedBankId(branchId) + "]");
                        //过滤掉没有找到机构号的记录
                        if (StringUtils.isBlank(bank.getBankCode()) || bank.getBankCode().equalsIgnoreCase("#N/A")) {
                            continue;
                        }

                        bi.setBankCode(bank.getBankCode());
                        bi.setCityId(area.getCityId());
                        bi.setProvId(area.getProvId());

                        parseResult.addSuccessResult(bi);

                        /* System.out.println(ToStringBuilder.reflectionToString(bi,
                             ToStringStyle.SHORT_PREFIX_STYLE));*/
                    } catch (Exception e) {
                        //                    Console.error("", e);
                        String errMessage = "branchId[" + branchId + "],解析出错:" + e.getMessage();
                        parseResult.addFailResult(branchId, errMessage);
                    }
                }
            }
        } catch (Exception e) {
            Console.error("", e);
        }
        return parseResult;
    }

    public static void main(String[] args) {
        String dataFile = "D:/WeibopayMemo/出款服务FOS/联行号信息.xml";
        Parser parser = new ICBCParser();
        File sourceDataFile = new File(dataFile);
        ParseResult rst = parser.parse(sourceDataFile);
        Console.info("{}", rst);
    }

}
